import logging
import re

import tornado
from tornado.httpserver import HTTPServer

import click

from class_broker import io_loop, make_app
# from webutils.openapi_doc import APIDoc, WSDoc
# from class_broker.routers import handlers
# from class_broker.app.ws.broker import text_message_handlers

logger = logging.getLogger('server')


@click.group()
def cli():
    pass


@cli.command()
@click.option('-b',
              '--bind',
              type=str,
              default='127.0.0.1:8888',
              help='you can use ip:port or unix sock')
@click.option('--debug',
              type=bool,
              default=False,
              help='enable debug mode or not')
@click.option('--log-filename',
              type=str,
              default='../logs/server.log')
@click.option('--log-level',
              type=str,
              default='INFO')
def runserver(bind, debug, log_filename, log_level):
    app = io_loop.asyncio_loop.run_until_complete(
        make_app(log_level, log_filename, debug=debug))
    ip_port_pattern = r'^\s*(?P<ip>(\d{1,3}\.){3}\d{1,3})'\
        r':(?P<port>\d{2,5})\s*$'
    match_res = re.match(ip_port_pattern, bind)
    if match_res:
        app.listen(int(match_res.group('port')), match_res.group('ip'))
    else:
        from tornado.netutil import bind_unix_socket
        server = HTTPServer(app)
        unix_socket = bind_unix_socket(bind)
        server.add_socket(unix_socket)
    logger.info(f'server start at {bind} with debug={debug}')
    tornado.ioloop.IOLoop.current().start()

# @cli.command()
# @click.option('-o',
#               '--output',
#               type=str,
#               default='../docs/api_doc/http.yaml',
#               help='where to save doc')
# @click.option('--strict',
#               type=bool,
#               default=True,
#               help='check generated api doc')
# def generate_http_doc(output, strict):
#     api_doc = APIDoc('class_broker/docs/api_doc/')
#     content = api_doc.generate_api_doc(handlers, strict=strict)
#     with open(output, 'w', encoding='utf8', newline='\n') as f:
#         f.write(content)


# @cli.command()
# @click.option('-o',
#               '--output',
#               type=str,
#               default='../docs/api_doc/websocket.yaml',
#               help='where to save doc')
# @click.option('--strict',
#               type=bool,
#               default=True,
#               help='check generated websocket doc')
# def generate_websocket_doc(output, strict):
#     ws_doc = WSDoc('class_broker/docs/websocket_doc/')
#     args = (text_message_handlers.act_handlers,
#             text_message_handlers.deliver_docs)
#     content = ws_doc.generate_api_doc(args, strict=strict)
#     with open(output, 'w', encoding='utf8', newline='\n') as f:
#         f.write(content)


if __name__ == '__main__':
    cli()
